import React, { useMemo, useCallback, useEffect } from 'react';
import { Button, Card, Divider, Form, Input } from 'antd';
import Store from 'store';
import { BottomAction } from '@/components';
import OrganizationSelect from '@/components/OrganizationSelect';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { defaultFormatResult, useRequest } from '@/hooks';
import useDictionary from '@/hooks/useDictionary';
import { formatResultByFetchDetail, onSuccessBySave } from '@/pages/TurnoverSetting/EntrySetting/util';
import pageTabUtil from '@/utils/pageTabUtil';
import useFormStorage from '@/hooks/useFormStorage';
import FormStorageStatus from '@/containers/FormStorageStatus';
import { TemplateEditor } from '../components';
import { getDefaultConfigByType, getGuideNoticeConfig, saveGuideNoticeConfig } from '../services';
import styles from './index.less';

/**
 * 入职须知模板编辑页
 */
const EntryGuideNoticeSettingEdit = ({ form, location }) => {
    const { query } = location;
    const { id } = query;
    const action = useMemo(() => (id ? 'edit' : 'create'), [id]);
    const actionName = useMemo(() => ({ edit: '编辑', create: '添加' }[action]), [action]);

    const [paramOfEntryNoteList] = useDictionary('paramOfEntryNote');
    const paramOfEntryNoteListTransformed = useMemo(() => {
        if (paramOfEntryNoteList) {
            return paramOfEntryNoteList.map(item => ({ field: item.value, value: item.text }));
        }
        return [];
    }, [paramOfEntryNoteList]);
    const [mainData, setMainData] = React.useState({});

    // 获取已存在的数据
    const { data, loading } = useRequest(() => getGuideNoticeConfig(id), {
        ready: action === 'edit' && id,
        formatResult: formatResultByFetchDetail
    });

    // 创建数据是, 获取默认配置
    const { data: defaultData, loading: defaultDataLoading } = useRequest(() => getDefaultConfigByType('4'), {
        ready: action === 'create',
        ...defaultFormatResult
    });

    // 保存数据
    const { run: submitRun, loading: submitLoading } = useRequest(submitData => saveGuideNoticeConfig(submitData), {
        manual: true,
        onSuccess: res => onSuccessBySave(res, { action, id, key: 'EntryGuideNoticeSetting', type: 'rmStorage' })
    });

    const handleSubmit = () => {
        form.validateFields(async (err, values) => {
            if (!err) {
                submitRun({ ...data, isDefault: data?.isDefault ?? 0, ...values });
            }
        });
    };
    const handlePreview = useCallback(() => {
        window.open('/office/personnelManagement/onboardAndLeave/setting/entryGuideNotice/preview');
        Store.set('EntryGuideNoticeSettingMailContent', { tplContent: form.getFieldValue('tplContent') });
    }, [form]);
    const { formData, status: formStorageStatus, isFirstTimeToPage, saveTime } = useFormStorage({
        form,
        action,
        id,
        key: 'EntryGuideNoticeSetting'
    });

    useEffect(() => {
        setMainData(formData || data);
    }, [data, formData]);

    return (
        <PageHeaderWrapper>
            <Card title={`${actionName}模板`} bordered={false} loading={loading || defaultDataLoading}>
                <FormStorageStatus
                    status={formStorageStatus}
                    isFirstTimeToPage={isFirstTimeToPage}
                    saveTime={saveTime}
                ></FormStorageStatus>
                <Form className={styles.formWrap}>
                    <Form.Item label="模板名称">
                        {form.getFieldDecorator('settingName', {
                            initialValue: mainData?.settingName || undefined,
                            rules: [
                                {
                                    required: true,
                                    message: '模板名称不能为空'
                                }
                            ]
                        })(<Input placeholder="请输入配置名称" allowClear maxLength={200} style={{ maxWidth: 528 }} />)}
                    </Form.Item>
                    <Form.Item label="适用行政机构">
                        {mainData?.isDefault === 1 && '全集团'}
                        {mainData?.isDefault === 1 &&
                            form.getFieldDecorator('administrativeScopes', {
                                initialValue: mainData?.administrativeScopes || undefined
                            })(<input type="hidden" />)}
                        {data?.isDefault !== 1 &&
                            form.getFieldDecorator('administrativeScopes', {
                                initialValue: mainData?.administrativeScopes || undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '适用行政机构不能为空'
                                    }
                                ]
                            })(
                                <OrganizationSelect
                                    treeCheckable
                                    isStrictly
                                    onlyCompany
                                    maxTagCount={2}
                                    style={{ maxWidth: 528 }}
                                    isNeedPermission={false}
                                    placeholder="请选择行政机构"
                                />
                            )}
                    </Form.Item>
                    <Form.Item label="模板内容">
                        {form.getFieldDecorator('tplContent', {
                            rules: [
                                {
                                    required: true,
                                    message: '模板内容不能为空'
                                }
                            ]
                        })(
                            <TemplateEditor
                                initialValue={mainData?.tplContent || defaultData?.tplContent || ''}
                                contentStyle={{ height: 'auto', minHeight: 250 }}
                                insertParamList={paramOfEntryNoteListTransformed} // 要参数的参数由外部引入
                            />
                        )}
                    </Form.Item>
                    <BottomAction>
                        <Button type="primary" ghost onClick={handlePreview}>
                            预览
                        </Button>
                        <Divider type="vertical" />
                        <Button onClick={() => pageTabUtil.goBack()}>取消</Button>
                        <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                            提交
                        </Button>
                    </BottomAction>
                </Form>
            </Card>
        </PageHeaderWrapper>
    );
};

EntryGuideNoticeSettingEdit.displayName = 'EntryGuideNoticeSettingEdit';

export default React.memo(Form.create()(EntryGuideNoticeSettingEdit));
